package com.fc.mall.portal.service.impl;

import com.fc.mall.base.object.Result;
import com.fc.mall.exception.ServiceException;
import com.fc.mall.mapper.*;
import com.fc.mall.model.*;
import com.fc.mall.mapper.*;
import com.fc.mall.portal.component.CancelOrderSender;
import com.fc.mall.portal.config.WspConfig;
import com.fc.mall.portal.dao.PortalOrderDao;
import com.fc.mall.portal.dao.PortalOrderItemDao;
import com.fc.mall.portal.dao.SmsCouponHistoryDao;
import com.fc.mall.portal.domain.*;
import com.fc.mall.portal.domain.*;
import com.fc.mall.portal.dto.OmsOrderQueryParam;
import com.fc.mall.portal.service.*;
import com.fc.mall.portal.vo.OmsOrderVO;
import com.fc.mall.portal.vo.OrderCountByStatusVO;
import com.fc.mall.portal.wechat.WXPayUtil;
import com.fc.mall.portal.wechat.dto.WXPaymentResponse;
import com.fc.mall.portal.wechat.dto.WxConfig;
import com.fc.mall.util.Constants;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.model.*;
import com.fc.mall.portal.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service
 * Created by dobuy on 2018/8/30.
 */
@Service
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
    private Logger logger = LoggerFactory.getLogger(OmsPortalOrderServiceImpl.class);
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private OmsCartItemService cartItemService;
    @Autowired
    private UmsMemberReceiveAddressService memberReceiveAddressService;
    @Autowired
    private UmsMemberCouponService memberCouponService;
    @Autowired
    private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private SmsCouponHistoryDao couponHistoryDao;
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private PortalOrderItemDao orderItemDao;
    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.orderId}")
    private String REDIS_KEY_PREFIX_ORDER_ID;
    @Autowired
    private PortalOrderDao portalOrderDao;
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private CancelOrderSender cancelOrderSender;
    @Autowired
    private OmsPromotionService promotionService;

    @Autowired
    private PmsProductMapper pmsProductMapper;

    @Autowired
    private PmsFeightTemplateMapper pmsFeightTemplateMapper;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private UmsMemberCommissionService memberCommissionService;

    @Autowired
    private SysPropertyConfigMapper sysPropertyConfigMapper;

    @Autowired
    private UmsMemberAccountChangeHistoryMapper umsMemberAccountChangeHistoryMapper;

    @Autowired
    private PmsDeliveryTemplateMapper deliveryTemplateMapper;

    @Autowired
    private UmsMemberAccountService memberAccountService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private WspConfig wspConfig;

    @Autowired
    private ConfigService configService;

    @Autowired
    private OmsOrderGroupService omsOrderGroupService;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private OmsOrderGroupBuyItemMapper orderGroupBuyItemMapper;

    @Autowired
    private OmsOrderGroupBuyMapper orderGroupBuyMapper;

    @Autowired
    private PmsProductGroupBuyMapper productGroupBuyMapper;

    @Autowired
    private OmsBargainMapper bargainMapper;

    @Autowired
    private UmsIntegrationService integrationService;

    @Autowired
    private UmsMemberUpgradeService umsMemberUpgradeService;

    @Override
    public OmsOrder getById(Long orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public OmsOrderVO getOrderVOById(Long orderId) {
        OmsOrderVO orderVO = new OmsOrderVO();
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderId);
        mapperFacade.map(omsOrder, orderVO);
        OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
        OmsOrderItemExample.Criteria orderItemExampleCriteria = orderItemExample.createCriteria();
        orderItemExampleCriteria.andOrderIdEqualTo(orderVO.getId());
        List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(orderItemExample);
        orderVO.setOmsOrderItemList(omsOrderItems);
        checkIsOrderGroup(orderVO);
        return orderVO;
    }

    @Override
    public ConfirmOrderResult generateConfirmOrder(String cartIds) {
        //根据购物车获取确认订单信息
        UmsMember currentMember = memberService.getCurrentMember();
        List<OmsCartItem> cartItemList = cartItemService.list(currentMember.getId(), cartIds);
        return generateConfirmOrder(cartItemList);
    }

    @Override
    public ConfirmOrderResult generateConfirmOrder(List<OmsCartItem> omsCartItems) {
        ConfirmOrderResult result = new ConfirmOrderResult();

        UmsMember currentMember = memberService.getCurrentMember();
        List<CartPromotionItem> cartPromotionItemList = promotionService.calcCartPromotion(omsCartItems);
        result.setCartPromotionItemList(cartPromotionItemList);


        //获取用户收货地址列表
        List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
        result.setMemberReceiveAddressList(memberReceiveAddressList);

        String defautAddress =  "";
        if(null != memberReceiveAddressList && memberReceiveAddressList.size()>0)
        {
            for(UmsMemberReceiveAddress address : memberReceiveAddressList)
            {
                if(address.getDefaultStatus().equals(1))
                {
                    defautAddress = address.getProvince();
                }
            }
        }

        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
        result.setCouponHistoryDetailList(couponHistoryDetailList);

        //获取用户积分
        result.setMemberIntegration(currentMember.getIntegration());

        //获取积分使用规则
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        result.setIntegrationConsumeSetting(integrationConsumeSetting);

        //计算总金额、活动优惠、应付金额
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList, defautAddress);
        result.setCalcAmount(calcAmount);
        return result;
    }

    @Override
    public Result generateOrder(OrderParam orderParam, String cartIds) {
        UmsMember currentMember = memberService.getCurrentMember();
        List<OmsCartItem> cartItemList = cartItemService.list(currentMember.getId(), cartIds);
        return generateOrder(orderParam, cartItemList);
    }

    @Override
    public Result generateOrder(OrderParam orderParam, List<OmsCartItem> omsCartItems) {
        List<OmsOrderItem> orderItemList = new ArrayList<>();

        UmsMember currentMember = memberService.getCurrentMember();
        List<CartPromotionItem> cartPromotionItemList = promotionService.calcCartPromotion(omsCartItems);
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            //生成下单商品信息
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(cartPromotionItem.getProductId());
            orderItem.setProductName(cartPromotionItem.getProductName());
            orderItem.setProductPic(cartPromotionItem.getProductPic());
            orderItem.setProductAttr(cartPromotionItem.getProductAttr());
            orderItem.setProductBrand(cartPromotionItem.getProductBrand());
            orderItem.setProductSn(cartPromotionItem.getProductSn());
            orderItem.setProductPrice(cartPromotionItem.getPrice());
            orderItem.setProductQuantity(cartPromotionItem.getQuantity());
            orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
            orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
            orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
            orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
            orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
            orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
            orderItem.setGiftGrowth(cartPromotionItem.getGrowth());
            orderItem.setSp1(cartPromotionItem.getSp1());
            orderItem.setSp2(cartPromotionItem.getSp2());
            orderItemList.add(orderItem);
        }
        //判断购物车中商品是否都有库存
        if (!hasStock(cartPromotionItemList)) {
            return Result.failed("库存不足，无法下单");
        }
        //判断使用使用了优惠券
        BigDecimal couponAmount = new BigDecimal(0.00);
        if (orderParam.getCouponId() == null) {
            //不用优惠券
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setCouponAmount(new BigDecimal(0));
            }
        } else {
            //使用优惠券
            SmsCouponHistoryDetail couponHistoryDetail = getUseCoupon(cartPromotionItemList, orderParam.getCouponId());
            if (couponHistoryDetail == null) {
                return Result.failed("该优惠券不可用");
            }
            //对下单商品的优惠券进行处理
            //handleCouponAmount(orderItemList, couponHistoryDetail);
            couponAmount = couponHistoryDetail.getCoupon().getAmount();
        }
        //判断是否使用积分
        if (orderParam.getUseIntegration() == null) {
            //不使用积分
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setIntegrationAmount(new BigDecimal(0));
            }
        } else {
            //使用积分
            BigDecimal totalAmount = calcTotalAmount(orderItemList);
            BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, orderParam.getCouponId() != null);
            if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
                return Result.failed("积分不可用");
            } else {
                //可用情况下分摊到可用商品中
                for (OmsOrderItem orderItem : orderItemList) {
                    BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3,RoundingMode.HALF_EVEN).multiply(integrationAmount);
                    orderItem.setIntegrationAmount(perAmount);
                }
            }
        }
        //计算order_item的实付金额
        handleRealAmount(orderItemList);
        //进行库存锁定
        lockStock(cartPromotionItemList);
        //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
        OmsOrder order = new OmsOrder();
        order.setDiscountAmount(new BigDecimal(0));
        order.setTotalAmount(calcTotalAmount(orderItemList));
        order.setFreightAmount(new BigDecimal(0));
        order.setPromotionAmount(calcPromotionAmount(orderItemList));
        order.setPromotionInfo(getOrderPromotionInfo(orderItemList));
        if (orderParam.getCouponId() == null) {
            order.setCouponAmount(new BigDecimal(0));
        } else {
            order.setCouponId(orderParam.getCouponId());
            // order.setCouponAmount(calcCouponAmount(orderItemList));
            order.setCouponAmount(couponAmount);
        }
        if (orderParam.getUseIntegration() == null) {
            order.setIntegration(0);
            order.setIntegrationAmount(new BigDecimal(0));
        } else {
            order.setIntegration(orderParam.getUseIntegration());
            order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
        }
        order.setPayAmount(calcPayAmount(order));
        //转化为订单信息并插入数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(new Date());
        String nickName = StringUtils.isEmpty(currentMember.getNickname()) ? "" : currentMember.getNickname();
        try {
            order.setMemberUsername(URLEncoder.encode(nickName, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(orderParam.getPayType());
        //订单来源：0->PC订单；1->app订单
        order.setSourceType(1);
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->正常订单；1->秒杀订单
        order.setOrderType(0);
        //收货人信息：姓名、电话、邮编、地址
        UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverPostCode(address.getPostCode());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        order.setNote(orderParam.getContent());
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        //计算赠送积分
        order.setIntegration(calcGifIntegration(orderItemList));
        //计算赠送成长值
        order.setGrowth(calcGiftGrowth(orderItemList));
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        // TODO: 2018/9/3 bill_*,delivery_*
        //插入order表和order_item表
        orderMapper.insert(order);
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
        }
        orderItemDao.insertList(orderItemList);
        //如使用优惠券更新优惠券使用状态
        if(orderParam.getCouponId()!=null){
            updateCouponStatus(orderParam.getCouponId(),currentMember.getId(),1);
        }
        //如使用积分需要扣除积分
        if(orderParam.getUseIntegration()!=null){
            order.setUseIntegration(orderParam.getUseIntegration());
            memberService.updateIntegration(currentMember.getId(),currentMember.getIntegration()-orderParam.getUseIntegration());
        }
        //删除购物车中的下单商品
        deleteCartItemList(cartPromotionItemList,currentMember);
        Map<String,Object> result = new HashMap<>();
        result.put("order",order);
        result.put("orderItemList",orderItemList);
        return Result.success("下单成功", result);
    }

    @Override
    public Result paySuccess(String orderNumber) {
        //修改订单支付状态
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andOrderSnEqualTo(orderNumber);
        List<OmsOrder> orders = orderMapper.selectByExample(example);
        if (null == orders || orders.isEmpty())
        {
            return Result.success("支付成功");
        }
        OmsOrder order = orders.get(0);
        if (order.getStatus() == 1) {
            return Result.success("支付成功");
        }
        OmsOrder newOrder = new OmsOrder();
        newOrder.setId(order.getId());
        newOrder.setStatus(1);
        newOrder.setPaymentTime(new Date());
        orderMapper.updateByPrimaryKeySelective(newOrder);
        //恢复所有下单商品的锁定库存，扣减真实库存
        OmsOrderDetail orderDetail = portalOrderDao.getDetail(order.getId());
        int count = portalOrderDao.updateSkuStock(orderDetail.getOrderItemList());
        updateProdSale(orderDetail);
        String productName = "";
        if(orderDetail.getOrderItemList() != null && !orderDetail.getOrderItemList().isEmpty())
        {
            productName = orderDetail.getOrderItemList().get(0).getProductName();
        }
        smsService.sendCreateOrderNotice(order.getMemberId(), order.getOrderSn(), productName, order.getPayAmount().toString(), DateTimeHelper.getStringFromDate(new Date(), DateTimeHelper.PAYLOAD_DATEONLY));
        /**
         * 处理团购订单
         */
        boolean isGroupOrder = omsOrderGroupService.handleOrderGroupPaySuccess(order.getId());
        /**
         * 会员下单成功锁粉
         */
        UmsMember member = memberService.getById(order.getMemberId());
        memberService.convertToEffectiveMember(member);
        //计算分佣。团购不分佣
        if (null != orderDetail.getOrderItemList() && order.getOrderType().intValue() == 0)
        {
            for (OmsOrderItem orderItem : orderDetail.getOrderItemList())
            {
                PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(orderItem.getProductId());

                Integer commissionRate = pmsProduct.getCommissionRate();
                if(null == commissionRate || commissionRate.intValue() == 0)
                {
                    continue;
                }
                //计算上线分成
                memberCommissionService.handlePurchaseCommission(order.getMemberId(), orderItem.getRealAmount().multiply(new BigDecimal(commissionRate)).multiply(new BigDecimal(orderItem.getProductQuantity())).intValue(), orderNumber);
            }
        }

        //积分获取
        //支付的金额（元）
        int payAmount = order.getPayAmount().intValue();
        integrationService.getIntegration(order.getMemberId(),
                Constants.SourceTypeEnum.TRADE, payAmount);

        return Result.success("支付成功",count);
    }

    @Override
    public Result cancelTimeOutOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        //查询超时、未支付的订单及订单详情
        List<OmsOrderDetail> timeOutOrders = portalOrderDao.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
        if(CollectionUtils.isEmpty(timeOutOrders)){
            return Result.failed("暂无超时订单");
        }
        //修改订单状态为交易取消
        List<Long> ids = new ArrayList<>();
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            ids.add(timeOutOrder.getId());
        }
        portalOrderDao.updateOrderStatus(ids,4);
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            //解除订单商品库存锁定
            portalOrderDao.releaseSkuStockLock(timeOutOrder.getOrderItemList());
            //修改优惠券使用状态
            updateCouponStatus(timeOutOrder.getCouponId(),timeOutOrder.getMemberId(),0);
            //返还使用积分
            if(timeOutOrder.getUseIntegration()!=null){
                UmsMember member = memberService.getById(timeOutOrder.getMemberId());
                memberService.updateIntegration(timeOutOrder.getMemberId(),member.getIntegration()+timeOutOrder.getUseIntegration());
            }
        }
        return Result.success();
    }

    @Override
    public void cancelOrder(Long orderId) {
        //查询为付款的取消订单
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andIdEqualTo(orderId).andStatusEqualTo(0).andDeleteStatusEqualTo(0);
        List<OmsOrder> cancelOrderList = orderMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(cancelOrderList)){
            return;
        }
        OmsOrder cancelOrder = cancelOrderList.get(0);
        if(cancelOrder!=null){
            //修改订单状态为取消
            cancelOrder.setStatus(4);
            orderMapper.updateByPrimaryKeySelective(cancelOrder);
            OmsOrderItemExample orderItemExample=new OmsOrderItemExample();
            orderItemExample.createCriteria().andOrderIdEqualTo(orderId);
            List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
            //解除订单商品库存锁定
            portalOrderDao.releaseSkuStockLock(orderItemList);
            //修改优惠券使用状态
            updateCouponStatus(cancelOrder.getCouponId(),cancelOrder.getMemberId(),0);
            //返还使用积分
            if(cancelOrder.getUseIntegration()!=null){
                UmsMember member = memberService.getById(cancelOrder.getMemberId());
                memberService.updateIntegration(cancelOrder.getMemberId(),member.getIntegration()+cancelOrder.getUseIntegration());
            }
        }
    }

    @Override
    public void sendDelayMessageCancelOrder(Long orderId) {
        //获取订单超时时间
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        long delayTimes = orderSetting.getNormalOrderOvertime()*60*1000;
        //发送延迟消息
        cancelOrderSender.sendMessage(orderId,delayTimes);
    }

    @Override
    public PageInfo<OmsOrderVO> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        OmsOrderExample orderExample = new OmsOrderExample();
        OmsOrderExample.Criteria orderCriteria = orderExample.createCriteria();
        orderCriteria.andMemberIdEqualTo(memberService.getCurrentMember().getId());
        if(queryParam.getOrderSn() != null && !"".equals(queryParam.getOrderSn())){
            orderCriteria.andOrderSnEqualTo(queryParam.getOrderSn());
        }
        if(queryParam.getCreateTimeFrom() != null ){
            orderCriteria.andCreateTimeGreaterThanOrEqualTo(new Date(queryParam.getCreateTimeFrom()));
        }
        if(queryParam.getCreateTimeTo() != null  )
        {
            orderCriteria.andCreateTimeLessThanOrEqualTo(new Date(queryParam.getCreateTimeTo()));
        }
        if(queryParam.getOrderType() != null && !"".equals(queryParam.getOrderType()))
        {
            orderCriteria.andOrderTypeEqualTo(queryParam.getOrderType());
        }
        if(queryParam.getStatus() != null && !"".equals(queryParam.getStatus()))
        {
            orderCriteria.andStatusEqualTo(queryParam.getStatus());
        }
        PageHelper.startPage(pageNum, pageSize);
        //根据订单创建时间降序排列
        orderExample.setOrderByClause("create_time DESC");
        List<OmsOrder> orderList = orderMapper.selectByExample(orderExample);

        List<OmsOrderVO> omsOrderVOList = mapperFacade.mapAsList(orderList, OmsOrderVO.class);
        //获取订单产品列表
        for (OmsOrderVO orderVO : omsOrderVOList) {
            OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
            OmsOrderItemExample.Criteria orderItemExampleCriteria = orderItemExample.createCriteria();
            orderItemExampleCriteria.andOrderIdEqualTo(orderVO.getId());
            List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(orderItemExample);
            orderVO.setOmsOrderItemList(omsOrderItems);
            checkIsOrderGroup(orderVO);
        }


        List<OmsOrderVO> list = omsOrderVOList.stream().filter(dto -> {
            if(null == queryParam.getStatus())
            {
                return true;
            }
            if(null == dto.getGroupStatus())
            {
                return true;
            }
            if(dto.getGroupStatus().intValue() > 0)
            {
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        return new PageInfo<>(omsOrderVOList);
    }


    @Override
    public OrderCountByStatusVO countOrderByStatus() {
        UmsMember currentMember = memberService.getCurrentMember();
        OrderCountByStatusVO statusVO = portalOrderDao.countOrderStatus(currentMember.getId());
        return statusVO;
    }

    @Override
    public WXPaymentResponse unifiedOrder(String orderNumber, String spbillCreateIp) {
        UmsMember currentMember = memberService.getCurrentMember();
        OmsOrderExample orderExample = new OmsOrderExample();
        OmsOrderExample.Criteria orderCriteria = orderExample.createCriteria();
        orderCriteria.andOrderSnEqualTo(orderNumber);
        List<OmsOrder> orderList =  orderMapper.selectByExample(orderExample);
        if (null == orderList || orderList.isEmpty())
        {
            throw new ServiceException("订单不存在！");
        }
        OmsOrder omsOrder = orderList.get(0);
        String isDebugStr = configService.getOptionalConfig(Constants.SysPropertyConfigName.PAYMENTDEBUG.getName(), "0");
        boolean isDebug = isDebugStr.equals("1");
        wxConfig.setDebug(isDebug);
        return WXPayUtil.unifiedOrder(wxConfig, omsOrder.getOrderSn(), omsOrder.getPayAmount(), currentMember.getWxOpenId(), spbillCreateIp);
    }

    @Override
    public String payCallback(String notifyXml) {
        String respXml = "";

        try
        {
            logger.debug(notifyXml, "notifyXml");
            Map<String, String> map = WXPayUtil.doXMLParse(notifyXml);

            String returnCode = map.get("return_code");

            logger.debug(returnCode, "returnCode");
            if ("SUCCESS".equals(returnCode)) {
                //验证签名是否正确
                //回调验签时需要去除sign和空值参数
                Map<String, String> validParams = WXPayUtil.paraFilter(map);
                String prestr = WXPayUtil.createLinkString(validParams);
                //根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等
                /**此处添加自己的业务逻辑代码start**/
                String outTradeNo = map.get("out_trade_no");

                paySuccess(outTradeNo);

                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                respXml = "<xml>"
                        + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>"
                        + "</xml> ";
            } else {
                logger.debug("faile======================", "come here");
                respXml = "<xml>"
                        + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]]></return_msg>"
                        + "</xml> ";
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            respXml = "<xml>"
                    + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>"
                    + "</xml> ";
        }
        return respXml;
    }

    @Override
    public String refundCallback(Map<String, String> notificationMap) {
        //这里写退款逻辑
        return null;
    }

    @Override
    public List<OmsOrderFromFans> getfansOrderList() {
        Long memberId = memberService.getCurrentMember().getId();
        List<OmsOrderFromFans> newOrderFromFansList = new ArrayList<>();
        List<OmsOrderFromFans> orderFromFansList = portalOrderDao.getFansOrderList(memberId);
        if(null != orderFromFansList)
        {
            for(OmsOrderFromFans order : orderFromFansList)
            {
                try {
                    order.setNickName(URLDecoder.decode(StringUtils.isEmpty(order.getNickName()) ? "未授权用户" : order.getNickName(), "utf-8"));
                    order.setIcon(StringUtils.isEmpty(order.getIcon()) ? Constants.DEFAULT_HEADPORTAL : order.getIcon());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                order.setOwner(null == order.getMemberId() ? false : order.getMemberId().equals(memberId));
                UmsMemberAccountChangeHistoryExample example = new UmsMemberAccountChangeHistoryExample();
                example.createCriteria().andOrderSnEqualTo(order.getOrderSn()).andMemberIdEqualTo(memberId);
                List<UmsMemberAccountChangeHistory> historyList = umsMemberAccountChangeHistoryMapper.selectByExample(example);
                if(null != historyList && historyList.size() >0)
                {
                    Long amount = 0L;
                    for (UmsMemberAccountChangeHistory history : historyList)
                    {
                        amount += history.getAmount();
                    }
                    order.setAmount(new BigDecimal(amount).divide(BigDecimal.valueOf(100)));
                    newOrderFromFansList.add(order);
                }
            }
        }
        return newOrderFromFansList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderStatus(String orderNumber, Integer status) {
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andOrderSnEqualTo(orderNumber);

        List<OmsOrder> omsOrders = orderMapper.selectByExample(example);
        if(null == omsOrders && omsOrders.isEmpty())
        {
            throw new ServiceException("当前订单不存在");
        }
        OmsOrder oldOrder = omsOrders.get(0);
        OmsOrder newOrder = new OmsOrder();
        newOrder.setId(oldOrder.getId());
        newOrder.setStatus(status);
        memberAccountService.changeMemberAccountToAble(oldOrder.getOrderSn());
        int count = orderMapper.updateByPrimaryKeySelective(newOrder);
        /**
         * 如果是确认收货。则会判断是否达到升级的要素
         *
         */
        if(status.equals(Constants.OrderStatus.HAS_RECEIVE.getValue()))
        {
            umsMemberUpgradeService.handleTradeUpgrade(oldOrder.getMemberId(), oldOrder.getId());
        }

        return count;
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    @Override
    public String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_KEY_PREFIX_ORDER_ID + date;
        Long increment = redisService.increment(key, 1);
        sb.append(date);
        sb.append(String.format("%02d",order.getSourceType()));
        sb.append(String.format("%02d",order.getPayType()));
        String incrementStr = increment.toString();
        if(incrementStr.length()<=6){
            sb.append(String.format("%06d",increment));
        }else{
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     * 删除下单商品的购物车信息
     */
    private void deleteCartItemList(List<CartPromotionItem> cartPromotionItemList, UmsMember currentMember) {
        List<Long> ids = new ArrayList<>();
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            ids.add(cartPromotionItem.getId());
        }
        cartItemService.delete(currentMember.getId(),ids);
    }

    /**
     * 计算该订单赠送的成长值
     */
    private Integer calcGiftGrowth(List<OmsOrderItem> orderItemList) {
        Integer sum=0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum=sum+orderItem.getGiftGrowth()*orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 计算该订单赠送的积分
     */
    private Integer calcGifIntegration(List<OmsOrderItem> orderItemList) {
        int sum=0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum+=orderItem.getGiftIntegration()*orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 将优惠券信息更改为指定状态
     * @param couponId 优惠券id
     * @param memberId 会员id
     * @param useStatus 0->未使用；1->已使用
     */
    private void updateCouponStatus(Long couponId, Long memberId,Integer useStatus) {
        if (couponId==null) {
            return;
        }
        //查询第一张优惠券
        SmsCouponHistoryExample example = new SmsCouponHistoryExample();
        example.createCriteria().andMemberIdEqualTo(memberId)
                .andCouponIdEqualTo(couponId).andUseStatusEqualTo(useStatus==0?1:0);
        List<SmsCouponHistory> couponHistoryList = couponHistoryMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(couponHistoryList)){
            SmsCouponHistory couponHistory = couponHistoryList.get(0);
            couponHistory.setUseTime(new Date());
            couponHistory.setUseStatus(useStatus);
            couponHistoryMapper.updateByPrimaryKeySelective(couponHistory);
        }
    }

    private void handleRealAmount(List<OmsOrderItem> orderItemList) {
        for (OmsOrderItem orderItem : orderItemList) {
            //原价-促销价格-优惠券抵扣-积分抵扣
            BigDecimal realAmount = orderItem.getProductPrice()
                    .subtract(orderItem.getPromotionAmount().divide(new BigDecimal(orderItem.getProductQuantity())))
                    .subtract(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(realAmount);
        }
    }

    /**
     * 获取订单促销信息
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(",");
        }
        String result = sb.toString();
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算订单应付金额
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount())
                .subtract(order.getIntegrationAmount());
        return payAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount());
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单活动优惠
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount());
            }
        }
        return promotionAmount;
    }

    /**
     * 获取可用积分抵扣金额
     *
     * @param useIntegration 使用的积分数量
     * @param totalAmount    订单总金额
     * @param currentMember  使用的用户
     * @param hasCoupon      是否已经使用优惠券
     */
    private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        //判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        //根据积分使用规则判断使用可用
        //是否可用于优惠券共用
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            //不可与优惠券共用
            return zeroAmount;
        }
        //是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        //是否超过订单抵用最高百分比
        BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2,RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠券优惠进行处理
     *
     * @param orderItemList       order_item列表
     * @param couponHistoryDetail 可用优惠券详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
        SmsCoupon coupon = couponHistoryDetail.getCoupon();
        if (coupon.getUseType().equals(0)) {
            //全场通用
            calcPerCouponAmount(orderItemList, coupon);
        } else if (coupon.getUseType().equals(1)) {
            //指定分类
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
            calcPerCouponAmount(couponOrderItemList, coupon);
        } else if (coupon.getUseType().equals(2)) {
            //指定商品
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
            calcPerCouponAmount(couponOrderItemList, coupon);
        }
    }

    /**
     * 对每个下单商品进行优惠券金额分摊的计算
     *
     * @param orderItemList 可用优惠券的下单商品商品
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for (OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠券面额
            orderItem.setCouponAmount(coupon.getAmount());
        }
    }

    /**
     * 获取与优惠券有关系的下单商品
     *
     * @param couponHistoryDetail 优惠券详情
     * @param orderItemList       下单商品
     * @param type                使用关系类型：0->相关分类；1->指定商品
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> result = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                categoryIdList.add(productCategoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        }
        return result;
    }

    /**
     * 获取该用户可以使用的优惠券
     *
     * @param cartPromotionItemList 购物车优惠列表
     * @param couponId              使用优惠券id
     */
    private SmsCouponHistoryDetail getUseCoupon(List<CartPromotionItem> cartPromotionItemList, Long couponId) {
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
        for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) {
            if (couponHistoryDetail.getCoupon().getId().equals(couponId)) {
                return couponHistoryDetail;
            }
        }
        return null;
    }

    /**
     * 计算总金额
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    /**
     * 锁定下单商品的所有库存
     */
    private void lockStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartPromotionItem.getProductSkuId());
            skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity());
            skuStockMapper.updateByPrimaryKeySelective(skuStock);
        }
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getRealStock() <= 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 计算购物车中商品的价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList, String deliveryAddress) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();

        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        BigDecimal freightAmount = new BigDecimal(0);
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            freightAmount = freightAmount.add(calcFeightAmount(cartPromotionItem, deliveryAddress));
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount());
        }
        calcAmount.setFreightAmount(freightAmount);
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));
        return calcAmount;
    }

    /**
     * 就算当算的费用
     * @param cartPromotionItem
     * @return
     */
    private BigDecimal calcFeightAmount(CartPromotionItem cartPromotionItem, String deliveryAddress)
    {
        PmsProduct product = pmsProductMapper.selectByPrimaryKey(cartPromotionItem.getProductId());
        if (null == product || null== product.getFeightTemplateId() || product.getFeightTemplateId().equals(0))
        {
            return new BigDecimal(0);
        }

        // FreightPayer: 1：卖家承担运费， 2：买家承担运费
        if(StringUtils.isEmpty(product.getFreightPayer()) || product.getFreightPayer().equalsIgnoreCase("1"))
        {
            return new BigDecimal(0);
        }

        PmsDeliveryTemplate deliveryTemplate = deliveryTemplateMapper.selectByPrimaryKey(product.getFeightTemplateId());
        //运费模板为空或者运费模板设置的邮费由卖家承担
        if(null == deliveryTemplate || deliveryTemplate.getIsFree().intValue() == 0)
        {
            return new BigDecimal(0);
        }

        PmsFeightTemplateExample example = new PmsFeightTemplateExample();
        example.createCriteria().andDeliveryTempIdEqualTo(deliveryTemplate.getId());

        List<PmsFeightTemplate> freightTemps = pmsFeightTemplateMapper.selectByExample(example);

        if(null == freightTemps || freightTemps.isEmpty())
        {
            return new BigDecimal(0);
        }

        // 筛选默认起步模板和有效模板
        PmsFeightTemplate defaultTemp = null;
        PmsFeightTemplate activeTemp = null;
        for(PmsFeightTemplate feightTemp : freightTemps)
        {
            if(feightTemp.getIsDefault().equals(1))
            {
                defaultTemp = feightTemp;
            }
            if(feightTemp.getDest().indexOf(deliveryAddress.replace("市","")) > -1)
            {
                activeTemp = feightTemp;
            }
        }

        if(null == defaultTemp && null == activeTemp)
        {
            return new BigDecimal(0);
        }

        // 最终结算是按照 匹配到的 模板计算
        if(null == activeTemp){
            activeTemp = defaultTemp;
        }

        BigDecimal totalFee = new BigDecimal(0);
        //按照件数 来计算邮费
        if(deliveryTemplate.getPriceType().intValue() == 0)
        {
            BigDecimal firstFee = activeTemp.getFirstFee();
            if(cartPromotionItem.getQuantity().intValue() <= activeTemp.getFirstWeight().intValue())
            {
                return firstFee;
            }
            BigDecimal chargingFee = BigDecimal.valueOf(cartPromotionItem.getQuantity()).subtract(activeTemp.getFirstWeight()).divide(activeTemp.getContinueWeight()).multiply(activeTemp.getContinmeFee());

            //Integer chargingFee = (cartPromotionItem.getQuantity().intValue() -activeTemp.getFirstWeight().intValue())/activeTemp.getContinueWeight().intValue()*activeTemp.getContinmeFee().intValue();
            totalFee = chargingFee.add(firstFee);
        }
        //按照重量来收费
        else
        {
            BigDecimal firstFee = activeTemp.getFirstFee();
            BigDecimal weight = product.getWeight();
            if(null==weight || weight.intValue()==0 || weight.compareTo(activeTemp.getFirstWeight()) < 1)
            {
                return firstFee;
            }
            /**
             * （起步付款 + （(总重量-起步重量）/ 增加阶梯重量）* 增量费用）* 商品个数
             */
            BigDecimal chargingFee = weight.subtract(activeTemp.getFirstWeight()).divide(activeTemp.getContinueWeight()).multiply(activeTemp.getContinmeFee());
            totalFee = chargingFee.add(firstFee).multiply(new BigDecimal(cartPromotionItem.getQuantity()));
        }



        return totalFee;
    }
    private int updateProdSale(OmsOrderDetail omsOrderDetail)
    {
        for(OmsOrderItem item : omsOrderDetail.getOrderItemList())
        {
            PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(item.getProductId());
            PmsProduct updateProduct = new PmsProduct();
            updateProduct.setId(item.getProductId());
            Integer oldSale = null == pmsProduct.getSale() ? 0 : pmsProduct.getSale();
            Integer sale = oldSale + item.getProductQuantity();
            updateProduct.setSale(sale);
            pmsProductMapper.updateByPrimaryKeySelective(updateProduct);
        }
        return 0;
    }


    private void checkIsOrderGroup(OmsOrderVO order)
    {
        /**
         * OrderType 1: 为团购订单
         */
        if(order.getOrderType().intValue() == 1)
        {
            OmsOrderGroupBuyItemExample itemExample = new OmsOrderGroupBuyItemExample();
            itemExample.createCriteria().andOrderIdEqualTo(order.getId());
            List<OmsOrderGroupBuyItem> itemList = orderGroupBuyItemMapper.selectByExample(itemExample);
            if(null != itemList && !itemList.isEmpty())
            {
                Long groubuyId = itemList.get(0).getOmsOrderGroupBuyId();
                OmsOrderGroupBuy orderGroupBuy = orderGroupBuyMapper.selectByPrimaryKey(groubuyId);
                order.setGroupProductId(orderGroupBuy.getProductGroupId());
                order.setGroupOrderId(groubuyId);

                PmsProductGroupBuy productGroupBuy = productGroupBuyMapper.selectByPrimaryKey(orderGroupBuy.getProductGroupId());
                if(order.getStatus().intValue() == 0)
                {
                    order.setGroupStatus(-1);
                    order.setGroupStatusTxt("待付款");
                }
                if(order.getStatus().intValue() == 1)
                {
                    order.setGroupStatus(0);
                    order.setGroupStatusTxt("买家已付款，等待成团");
                    order.setMemberCount(productGroupBuy.getGroupCount() - orderGroupBuy.getMemberCount());
                    order.setExpiredTime(orderGroupBuy.getExpiredTime());
                }

                if(orderGroupBuy.getStatus() == 2)
                {
                    order.setGroupStatus(1);
                    order.setGroupStatusTxt("已成团，等待卖家发货");
                }

                if(order.getStatus().intValue() == 2)
                {
                    order.setGroupStatus(2);
                    order.setGroupStatusTxt("商家已发货");
                }

                if(order.getStatus().intValue() == 3)
                {
                    order.setGroupStatus(3);
                    order.setGroupStatusTxt("交易完成");
                }

                if(order.getStatus().intValue() == 4)
                {
                    order.setGroupStatus(-2);
                    order.setGroupStatusTxt("交易关闭");
                }
            }
            else
            {
                order.setGroupStatus(-3);
                order.setGroupStatusTxt("交易关闭");
            }


        }
        if(order.getOrderType().intValue() == 2)
        {
            OmsBargainExample bargainExample = new OmsBargainExample();
            bargainExample.createCriteria().andIsAddorderEqualTo(1)
                    .andOrderIdEqualTo(order.getId());

            List<OmsBargain> omsBargainList =  bargainMapper.selectByExample(bargainExample);
            if(omsBargainList.isEmpty())
            {
                order.setBargainId(0L);
            }
            else
            {
                order.setBargainId(omsBargainList.get(0).getId());
            }
        }
    }
}
